package com.controller.app;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.apidoc.annotation.Api;
import com.apidoc.annotation.ApiAction;
import com.apidoc.annotation.ApiParam;
import com.apidoc.annotation.ApiReqParams;
import com.apidoc.annotation.ApiRespParams;
import com.apidoc.enumeration.DataType;
import com.apidoc.enumeration.Method;
import com.apidoc.enumeration.ParamType;
import com.controller.vo.PersonVo;
import com.service.ILoginService;
import com.utils.Employee;
import com.utils.commons.LoginContextUtils;
import com.utils.commons.RandomUtils;
import com.utils.commons.ResponseBean;
import com.utils.enums.ENUM_SUCESS;

@Api(name = "登录管理", order = 1, mapping = "/wx/login")
@Controller
@RequestMapping("/wx/login")
public class WxLoginController {

	@Autowired
	private ILoginService loginService;
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@ApiAction(name = "验证帐号是否可用", order = 1, mapping = "/testAccount", method = Method.POST)
	@ApiReqParams(type = ParamType.URL_PARAM, value = {
			@ApiParam(name = "account", dataType = DataType.STRING, defaultValue = "", description = "帐号"),
            @ApiParam(name = "type", dataType = DataType.NUMBER, defaultValue = "0:管理员,1:普通,2:贷后,3:专员", description = "类型")
    })
    @ApiRespParams({
            @ApiParam(name = "status", dataType = DataType.NUMBER, defaultValue = "", description = "状态码"),
            @ApiParam(name = "data", dataType = DataType.OBJECT, defaultValue = "", description = "响应数据"),
            @ApiParam(name = "text", dataType = DataType.STRING, defaultValue = "", description = "提示信息")
    })
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "/testAccount", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String testAccount(String account, String type) {
		if(loginService.hasAccount(account, type)) {
			return ResponseBean.of(ENUM_SUCESS.USED.value, "手机号已经注册过了");
		}
		return ResponseBean.of(ENUM_SUCESS.SUCESS.value);
	}
	
	/**
	 * 发送验证码
	 * @param account
	 * @param type 人员类型
	 * @return
	 */
	@ApiAction(name = "发送验证码", order = 1, mapping = "/sendValicode", method = Method.POST)
	@ApiReqParams(type = ParamType.URL_PARAM, value = {
			@ApiParam(name = "account", dataType = DataType.STRING, defaultValue = "", description = "手机号(账号)"),
            @ApiParam(name = "type", dataType = DataType.NUMBER, defaultValue = "0:管理员,1:普通,2:贷后,3:专员",required=false, description = "类型,不传即不验证帐号重复")
    })
    @ApiRespParams({
            @ApiParam(name = "status", dataType = DataType.NUMBER, defaultValue = "", description = "状态码"),
            @ApiParam(name = "data", dataType = DataType.OBJECT, defaultValue = "", description = "响应数据", object="map"),
            @ApiParam(name = "valiCode", dataType = DataType.STRING, defaultValue = "", description = "验证码", belongTo="map"),
            @ApiParam(name = "text", dataType = DataType.STRING, defaultValue = "", description = "提示信息")
    })
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "/sendValicode", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String sendValicode(String account, String type) {
		String random = RandomUtils.getRandNum(6);
		if(!StringUtils.isEmpty(type) && loginService.hasAccount(account, type)) {
			return ResponseBean.of(null, ENUM_SUCESS.USED.value, "手机号已经注册过了");
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("valiCode", random);
		ValueOperations<String, String> vop = stringRedisTemplate.opsForValue();
		vop.set(account, random, 5, TimeUnit.MINUTES);
		return ResponseBean.of(map, ENUM_SUCESS.SUCESS.value);
	}
	
	/**
	 * 注册
	 * @param account
	 * @param password
	 * @param type
	 * @param valiCode
	 * @return
	 */
	@ApiAction(name = "注册", order = 1, mapping = "/register", method = Method.POST)
	@ApiReqParams(type = ParamType.URL_PARAM, value = {
			@ApiParam(name = "account", dataType = DataType.STRING, defaultValue = "", description = "帐号"),
            @ApiParam(name = "password", dataType = DataType.STRING, defaultValue = "", description = "密码"),
            @ApiParam(name = "openId", dataType = DataType.STRING, defaultValue = "", description = "openId"),
            @ApiParam(name = "type", dataType = DataType.STRING, defaultValue = "0:管理员,1:普通,2:贷后,3:专员", description = "类型"),
            @ApiParam(name = "valiCode", dataType = DataType.STRING, defaultValue = "", description = "验证码")
    })
    @ApiRespParams({
            @ApiParam(name = "status", dataType = DataType.NUMBER, defaultValue = "", description = "状态码"),
            @ApiParam(name = "data", dataType = DataType.OBJECT, defaultValue = "", description = "响应数据", object="PersonVo"),
            @ApiParam(name = "account", dataType = DataType.STRING, defaultValue = "", description = "帐号", belongTo="PersonVo"),
            @ApiParam(name = "password", dataType = DataType.STRING, defaultValue = "", description = "密码", belongTo="PersonVo"),
            @ApiParam(name = "role", dataType = DataType.NUMBER, defaultValue = "", description = "类型0:管理员,1:普通,2:贷后,3:专员", belongTo="PersonVo"),
            @ApiParam(name = "userName", dataType = DataType.STRING, defaultValue = "", description = "名字", belongTo="PersonVo"),
            @ApiParam(name = "openId", dataType = DataType.STRING, defaultValue = "", description = "openId", belongTo="PersonVo"),
            @ApiParam(name = "text", dataType = DataType.STRING, defaultValue = "", description = "提示信息")
    })
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "/register", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String registerPerson(String account, String password, String openId, String type, String valiCode){
		String result;
		try {
			if(stringRedisTemplate.hasKey(account)) {
				ValueOperations<String, String> vop = stringRedisTemplate.opsForValue();
				if(!ObjectUtils.isEmpty(valiCode) && !valiCode.equals(vop.get(account))){
					return ResponseBean.of(null, ENUM_SUCESS.ERROR.value, "验证码错误");
				}
				stringRedisTemplate.delete(account);
			}else {
				return ResponseBean.of(null, ENUM_SUCESS.TIMEOUT.value, "验证码失效");
			}
			result = ResponseBean.of(loginService.registerPerson(account, password, openId, type), ENUM_SUCESS.SUCESS.value, "注册成功");
		} catch (Exception e) {
			e.printStackTrace();
			result = ResponseBean.of(ENUM_SUCESS.FAILED.value, e.getMessage());
		}
		return result;
	}
	
	/**
	 * 登录
	 * @param account
	 * @param password
	 * @return
	 */
	@ApiAction(name = "登录", order = 1, mapping = "/login", method = Method.POST)
	@ApiReqParams(type = ParamType.URL_PARAM, value = {
			@ApiParam(name = "account", dataType = DataType.STRING, defaultValue = "", description = "帐号"),
            @ApiParam(name = "password", dataType = DataType.STRING, defaultValue = "", description = "密码"),
            @ApiParam(name = "openId", dataType = DataType.STRING, defaultValue = "", description = "openId,首先使用账号密码登录"),
            @ApiParam(name = "type", dataType = DataType.NUMBER, required = true, defaultValue = "0:管理员,1:普通,2:贷后,3:专员", description = "类型")
    })
    @ApiRespParams({
            @ApiParam(name = "status", dataType = DataType.NUMBER, defaultValue = "", description = "状态码"),
            @ApiParam(name = "data", dataType = DataType.OBJECT, defaultValue = "", description = "响应数据", object="PersonVo"),
            @ApiParam(name = "account", dataType = DataType.STRING, defaultValue = "", description = "帐号", belongTo="PersonVo"),
            @ApiParam(name = "password", dataType = DataType.STRING, defaultValue = "", description = "密码", belongTo="PersonVo"),
            @ApiParam(name = "text", dataType = DataType.STRING, defaultValue = "", description = "提示信息")
    })
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "/login", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String personLogin(String account, String password, String openId, String type, HttpServletRequest request){
		String res;
		try {
			PersonVo ps = loginService.login(account, password, openId, type);
			ps.setPassword(password);
			Employee emp = new Employee(ps);
			LoginContextUtils.setLoginUser(emp, request.getSession());
			res = ResponseBean.of(ps,ENUM_SUCESS.SUCESS.value,"登录成功");
		} catch (Exception e) {
			res = ResponseBean.of(ENUM_SUCESS.FAILED.value, e.getMessage());
		}
		return res;
	}
	
	@ApiAction(name = "忘记密码", order = 1, mapping = "/forgotten", method = Method.POST)
	@ApiReqParams(type = ParamType.URL_PARAM, value = {
			@ApiParam(name = "account", dataType = DataType.STRING, defaultValue = "", description = "帐号"),
            @ApiParam(name = "password", dataType = DataType.STRING, defaultValue = "", description = "新的密码"),
            @ApiParam(name = "valiCode", dataType = DataType.STRING, defaultValue = "", description = "验证码"),
            @ApiParam(name = "type", dataType = DataType.NUMBER, defaultValue = "0:管理员,1:普通,2:贷后,3:专员", description = "类型")
    })
    @ApiRespParams({
            @ApiParam(name = "status", dataType = DataType.NUMBER, defaultValue = "", description = "状态码"),
            @ApiParam(name = "data", dataType = DataType.OBJECT, defaultValue = "", description = "响应数据"),
            @ApiParam(name = "text", dataType = DataType.STRING, defaultValue = "", description = "提示信息")
    })
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "/forgotten", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String forgetPassword(String account, String password, String valiCode, String type){
		try {
			if(stringRedisTemplate.hasKey(account)) {
				ValueOperations<String, String> vop = stringRedisTemplate.opsForValue();
				if(!ObjectUtils.isEmpty(valiCode) && !valiCode.equals(vop.get(account))){
					return ResponseBean.of(ENUM_SUCESS.ERROR.value, "验证码错误");
				}
				stringRedisTemplate.delete(account);
			}else {
				return ResponseBean.of(ENUM_SUCESS.TIMEOUT.value, "验证码失效");
			}
			loginService.forgetPassword(account, password, type);
		} catch (Exception e) {
			return ResponseBean.of(ENUM_SUCESS.FAILED.value, e.getMessage());
		}
		return ResponseBean.of(null, ENUM_SUCESS.SUCESS.value, "修改密码成功");
	}
	
	@ApiAction(name = "获取openId", order = 1, mapping = "/getOpenId", method = Method.POST)
	@ApiReqParams(type = ParamType.URL_PARAM, value = {
			@ApiParam(name = "code", dataType = DataType.STRING, defaultValue = "", required = true, description = "code")
    })
    @ApiRespParams({
            @ApiParam(name = "status", dataType = DataType.NUMBER, defaultValue = "", description = "状态码"),
            @ApiParam(name = "data", dataType = DataType.OBJECT, defaultValue = "", description = "响应数据", object="openid"),
            @ApiParam(name = "openid", dataType = DataType.OBJECT, defaultValue = "", description = "openid", belongTo="openid"),
            @ApiParam(name = "errcode", dataType = DataType.OBJECT, defaultValue = "", description = "微信返回的错误码", belongTo="openid"),
            @ApiParam(name = "errmsg", dataType = DataType.OBJECT, defaultValue = "", description = "微信返回的错误信息", belongTo="openid"),
            @ApiParam(name = "text", dataType = DataType.STRING, defaultValue = "", description = "提示信息")
    })
	@CrossOrigin(origins = "*")
	@RequestMapping(value = "/getOpenId", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getOpenId(String code) {
		try {
			return ResponseBean.of(loginService.getAccess_token(code), ENUM_SUCESS.SUCESS.value);
		} catch (Exception e) {
			return ResponseBean.of(ENUM_SUCESS.FAILED.value, e.getMessage());
		}
	}
}
